package com.boot.mapper;

import com.boot.entity.Address;
import com.boot.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

//@Mapper:让SpringBoot自动扫描识别到它
@Mapper
public interface UserMapper {
    //新增、修改、查询、更新
    @Insert("insert into t_user(userName,password) values(#{userName},#{password})")
    int save(User user);

    @Select("select id,addTime,userName,password from t_user")
    @Results(id = "baseResultMap",value =
            {
                @Result(id = true,column = "id",property = "id"),
                @Result(column = "addTime",property = "addTime"),
                @Result(column = "userName",property = "userName"),
                @Result(column = "password",property = "password"),
                @Result(column = "address_id",property = "address",one = @One(select = "com.boot.mapper.AddressMapper.getById")),
                @Result(column = "id",property = "menus", many = @Many(select = "com.boot.mapper.MenuMapper.getByUserId"))
            }
    )
    List<User> selectAll();

    @Select("select id,addTime,userName,password,address_id from t_user where id = #{id}")
    /*@Results(
            {
                    @Result(id = true,column = "id",property = "id"),
                    @Result(column = "addTime",property = "addTime"),
                    @Result(column = "userName",property = "userName"),
                    @Result(column = "password",property = "password")
            }
    )*/
    @ResultMap(value="baseResultMap")
    User selectById(Long id);

    //新增完成之后 将id回填到user对象中
    //select last_insert_id():在同一个事务中 刚刚新增完成后的主键ID是可以查询到的
    //keyProperty:User类的id属性
    //resultType:User类的id类型
    //before:false 在插入之后
    @Insert("insert into t_user(userName,password) values(#{userName},#{password})")
    @SelectKey(statement = "select last_insert_id()", keyProperty = "id", keyColumn = "id", resultType = Long.class,before = false)
    public int insert2(User user);

    @Update("update t_user set userName= #{userName}, password = #{password} where id = #{id}")
    void updateUserById(User user);

}
